#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

#define SOCKET_ERROR        -1
#define BUFFER_SIZE         100
#define HOST_NAME_SIZE      255

FILE* 	logfile=NULL;
int	runcond=1;
int hSocket;                 /* handle to socket */

void sighandler()
{
	printf("killed by handler\n");
	runcond=0;
	fclose(logfile);
	if(close(hSocket) == SOCKET_ERROR)
	{
		printf("\nCould not close socket\n");
	}
	_exit(0);
}

int  main(int argc, char* argv[])
{
	struct hostent* pHostInfo;   /* holds info about a machine */
	struct sockaddr_in Address;  /* Internet socket address stuct */
	long nHostAddress;
	char pBuffer[BUFFER_SIZE];
	unsigned nReadAmount;
	char strHostName[HOST_NAME_SIZE];
	int nHostPort;

	strcpy(strHostName, "localhost");
	nHostPort=20000;

	/* make a socket */
	hSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

	if(hSocket == SOCKET_ERROR)
	{
		printf("Could not make a socket\n");
		return 0;
	}
	/* get IP address from name */
	pHostInfo=gethostbyname(strHostName);
	/* copy address into long */
	memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length);

	/* fill address struct */
	Address.sin_addr.s_addr=nHostAddress;
	Address.sin_port=htons(nHostPort);
	Address.sin_family=AF_INET;

	/* connect to host */
	if(connect(hSocket,(struct sockaddr*)&Address,sizeof(Address)) == SOCKET_ERROR)
	{
		printf("\nCould not connect to host\n");
		return 0;
	}

	logfile=fopen("./logfile", "a");
	if(NULL==logfile)
	{
		printf("couldn't open logfile for writing :(\n");
		_exit(1);
	}

	signal(SIGPIPE, sighandler);
	signal(SIGTERM, sighandler);
	signal(SIGINT, sighandler);

/*demonize*/
	int cpid = fork ();
	if (cpid)
	_exit(0);
	close(0);
	close(1);
	close(2); 
 
	while(runcond)
	{
		nReadAmount=read(hSocket,pBuffer,BUFFER_SIZE);
		if(0>=nReadAmount)
		break;
		fprintf(logfile, "%s", pBuffer);
		fflush(logfile);
	} 

	printf("\nClosing socket\n");
	/* close socket */                       
	if(close(hSocket) == SOCKET_ERROR)
	{
		printf("\nCould not close socket\n");
	}
	return 0;
}
